<?php

declare(strict_types=1);

namespace App\Utils\Control;

use Hyperf\Coroutine\Coroutine;

/**
 * 用户登录信息验证
 */
class AuthUser{
    // 用户登录信息
    protected array $USER = [];//用户信息

    protected static array $instance = [];

    public static function getInstance(): AuthUser
    {
        //协程id
        $coroutine_id = Coroutine::id();
        if (empty(self::$instance[$coroutine_id])) {
            self::$instance[$coroutine_id] = new self();

            Coroutine::defer(function () use ($coroutine_id) {
                unset(self::$instance[$coroutine_id]);
            });
        }
        return self::$instance[$coroutine_id];
    }

    /**
     * 获取
     * @param array $user
     * @return void
     */
    public function set(array $user)
    {
        $this->USER = $user;
    }

    /**
     * 获取用户登录信息
     * @param string $key 用户字段，填写则获取固定字段值，不填写则返回全部
     * @return array|mixed|string
     */
    public function get(string $key = '')
    {
        if (!empty($key)){
            $field = $this->USER[$key] ?? '';
        }
        
        return $field ?? $this->USER;
    }

    /**
     * 校验
     * @return bool
     */
    public function check(): bool
    {
        if (empty($this->USER)) return false;
        return true;
    }
}